//
//  GKHistoryData.swift
//  MySwiftObject
//
//  Created by wangws1990 on 2018/9/11.
//  Copyright © 2018 wangws1990. All rights reserved.
//

import UIKit

class GKHistoryData {
    public static func updateChap(bookId :String, chap :Int,page :Int,completion:@escaping ((_ success : Bool) -> ())){
        BaseHistoryQueue().updateChapterIndex(bookId: bookId, chap: chap, page: page, completion: completion)
    }
    public static func updateBook(bookId :String, bookInfo :String,completion:@escaping ((_ success : Bool) ->())){
        BaseHistoryQueue().updateBook(bookId: bookId, bookInfo: bookInfo, completion: completion)
    }
    public static func updateChapterDatas(bookId :String,chapters :String?,completion:@escaping ((_ success : Bool) -> Void)){
        if let js = chapters{
            BaseHistoryQueue().updateChapData(bookId: bookId, chapData: js.data(using: .utf8), completion: completion)
        }
    }
    public static func getCacheChapters(bookId :String,loadNet :Bool = false,completion:@escaping ((_ model : GKHistory?) -> ())){
        if loadNet{
            GKCacheData.listChapter(bookId: bookId) { listData in
                let history = GKHistory()
                history.bookId = bookId
                history.chapters = listData
                DispatchQueue.main.async {
                    completion(history)
                }
            }
        }else{
            DispatchQueue.global().async {
                getHistory(bookId: bookId, needChapter: true) { model in
                    if let his = model,let _ = his.chapters{
                        DispatchQueue.main.async {
                            completion(his)
                        }
                    }else{
                        GKCacheData.listChapter(bookId: bookId) { listData in
                            let history = GKHistory()
                            history.bookId = bookId
                            history.chapters = listData
                            DispatchQueue.main.async {
                                completion(history)
                            }
                        }
                    }
                }
            }
        }
    }
    public static func getHistory(bookId :String,needChapter :Bool,completion:@escaping ((_ model : GKHistory?) -> ())){
        BaseHistoryQueue().getData(bookId: bookId, needChapter: needChapter, completion: completion)
    }
    public static func getHistoryData(completion:@escaping ((_ listData : [GKHistory]) ->())){
        BaseHistoryQueue().getData(completion: completion)
    }
}
